<?php
function fnmatch2($pattern, $string) {
	for ($op = 0, $npattern = '', $n = 0, $l = strlen($pattern); $n < $l; $n++) {
		switch ($c = $pattern[$n]) {
			case '\\':
				$npattern .= '\\' . @$pattern[++$n];
				break;
			case '.': case '+': case '^': case '$': case '(': case ')': case '{': case '}': case '=': case '!': case '<': case '>': case '|':
				$npattern .= '\\' . $c;
				break;
			case '?': case '*':
				$npattern .= '.' . $c;
				break;
			case '[': case ']': default:
				$npattern .= $c;
				if ($c == '[') {
					$op++;
				} else if ($c == ']') {
					if ($op == 0) return false;
					$op--;
				}
				break;
		}
	}

	if ($op != 0) return false;

	return preg_match('/' . $npattern . '/i', $string);
}

function display($list, $query) {
	$count = 0;
	$parsed = array();
	$query_array = split(':', $query);
	foreach($list as $row) {
		$matched = 0;
		//$matched = fnmatch2($row['img_name']);
		
		//$matched = fnmatch2($query[1], $row[$query[0]]);
		// uncomment to restore old matching code

		foreach($row as $key => $value) {
			//echo "{$key}:{$value}|"; // debug
			if(fnmatch2($query, $value)){
				$matched = 1;
			}
		}
		if ($matched) {
			if(!in_array($row['img_name'],$parsed)) {
				$parsed[$count] = $row['img_name'];
				$count++;
			}
		}
	}
	echo "<p>{$count} results found for query \"{$query}\":</p>";
	foreach ($parsed as $row) {
		$name = $row;
		echo "<div id=\"{$name}\" onclick=\"javascript:plot('{$name}')\">{$name}</div>";
	}
}

$query = $_GET['q'];
$sqlserver = mysql_connect('localhost','wustl_inst', 'wustl_pass');
if ($sqlserver != NULL) {
	$userdb = mysql_select_db('amos', $sqlserver);
	$d_query = urldecode($query);
	if (true) {
		$listquery = mysql_query("select * from HIT3", $sqlserver);
	}
	/*
	else {
		$d_query = urldecode($query);
		$listquery = mysql_query("select * from HIT2 where ".$d_query, $sqlserver);
	}
	*/
	$counter = 0;
	while($row = mysql_fetch_array($listquery, MYSQL_ASSOC)) {
		$list[$counter] = $row;
		$counter++;
	}
	
	display($list,$d_query);
}

?>